package com.smile.frame.config.rabbit.component;

import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;

import java.io.IOException;


/**
 * @author LGC
 */
@Slf4j
public class BasicHandler {

    /**
     * 成功处理
     */
    public void basicAck(Channel channel, Message message) throws IOException {
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }

    /**
     * 失败处理
     */
    public void exceptionHandler(Channel channel, Message message, Exception e) throws IOException {
        log.error("发生异常:message{}", new String(message.getBody()), e);
        exceptionHandler(channel, message);
    }

    /**
     * 失败处理
     */
    public void exceptionHandler(Channel channel, Message message) throws IOException {
        if (message.getMessageProperties().getRedelivered()) {
            log.error("消息已重复处理失败,拒绝再次接收");
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), false);
        } else {
            log.error("消息即将再次返回队列处理");
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
        }
    }
}
